package com.xbongbong.paas.help.subform.abstracts;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.FieldTypeEnum;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 子表单es和数据库格式转化父类
 * @author 魏荣杰
 * @date 2020/8/24 16:42
 * @since
 * @version
 */
public abstract class AbstractTransferSubForm {

    public void formatDataForEs(JSONObject dbJson, JSONObject data, String dbAttr, String dataAttr, Integer fieldType) {
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (Objects.nonNull(fieldTypeEnum)) {
            switch (fieldTypeEnum) {
                case TEXT:
                    data.put(dataAttr, dbJson.getString(dbAttr));
                    break;
                case LONG:
                    data.put(dataAttr, dbJson.getLong(dbAttr));
                    break;
                case NUM:
                case DATETIME:
                    Object o = dbJson.get(dbAttr);
                    if (o instanceof Double || o instanceof BigDecimal) {
                        data.put(dataAttr, dbJson.get(dbAttr));
                    } else {
                        data.put(dataAttr, dbJson.getLong(dbAttr));
                    }
                    break;
                default:
            }
        }
    }

    public void formatDataForDb(JSONObject data, JSONObject dbData, String dbAttr, String dataAttr, Integer fieldType) {
        if (Objects.isNull(data)) {
            return;
        }
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (Objects.nonNull(fieldTypeEnum)) {
            Object value = data.get(dataAttr);
            if (Objects.nonNull(value)) {
                switch (fieldTypeEnum) {
                    case TEXT:
                        dbData.put(dbAttr, value.toString());
                        break;
                    case LONG:
                        dbData.put(dbAttr, Long.valueOf(value.toString()));
                        break;
                    case NUM:
                        if (value instanceof Double || value instanceof BigDecimal) {
                            dbData.put(dbAttr, value);
                        } else {
                            dbData.put(dbAttr, Long.valueOf(value.toString()));
                        }
                        break;
                    case DATETIME:
                        dbData.put(dbAttr, Long.valueOf(value.toString()));
                        break;
                    default:
                }
            }
        }
    }
}
